package com.yctan.base.service;

import com.github.pagehelper.PageHelper;
import com.yctan.base.entity.BaseEntity;
import com.yctan.base.mapper.BaseMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 *
 * @author jeeplus
 * @version 2017-05-16
 */
@Transactional()
public abstract class BaseService<M extends BaseMapper<T>, T extends BaseEntity> {

    /**
     * 日志对象
     */
    protected Log LOG = LogFactory.getLog(getClass());

    /**
     * 持久层对象
     */

    @Autowired
    protected M mapper;

    /**
     * 获取单条数据
     *
     * @param id
     * @return
     */
    public T get(Integer id) {
        if (id == null) {
            return null;
        }
        return mapper.get(id);
    }

    /**
     * 获取单条数据
     *
     * @param entity
     * @return
     */
    public T get(T entity) {
        if (entity == null) {
            return null;
        }
        return mapper.get(entity);
    }

    /**
     * 查询列表数据
     *
     * @param entity
     * @return
     */
    public List<T> findList(T entity) {
        //分页
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        return mapper.findList(entity);
    }

    /**
     * 插入数据
     *
     * @param entity
     * @return
     */
    public void insert(T entity) {
        //插入前操作
        entity.preInsert();
        mapper.insert(entity);
    }

    /**
     * 更新数据
     *
     * @param entity
     * @return
     */
    public void update(T entity) {
        //更新前操作
        entity.preUpdate();
        mapper.update(entity);
    }

    /**
     * 删除数据
     */
    @Transactional(readOnly = false)
    public void delete(Integer id) {
        if (id != null) {
            mapper.delete(id);
        }
    }

    /**
     * 逻辑删除数据
     *
     * @param entity
     */
    @Transactional(readOnly = false)
    public int deleteByLogic(T entity) {
        return mapper.deleteByLogic(entity);
    }


}
